﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NFox;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Runtime;
using System.Windows.Interop;
using PInvoke;
using Autodesk.AutoCAD.Windows;
using LabelBar.View;

namespace LabelBar
{
    public class Funcommand : IExtensionApplication
    {
        MainView window;

        public void setwindow()  //设置窗口
        {

            try
            {
                window.Show();
                POINT pt = new POINT();
                PInvoke.User32.ScreenToClient(Application.DocumentManager.MdiActiveDocument.Window.Handle, ref pt);
                window.Left = pt.x;
                window.Top = pt.y;

                var handle = new WindowInteropHelper(window).Handle;
                PInvoke.User32.SetParent(handle, Application.DocumentManager.MdiActiveDocument.Window.Handle);
                PInvoke.User32.MoveWindow(handle, pt.x, pt.y, Application.DocumentManager.MdiActiveDocument.Window.GetSize().Width, 25, true);
            }
            catch (System.Exception)
            {

              
            }
         

        }

        public Funcommand()
        {
            window = new MainView(); // CAD不会崩溃
            Application.DocumentManager.DocumentDestroyed += DocumentManager_DocumentDestroyed;
            Application.DocumentManager.DocumentActivationChanged += DocumentManager_DocumentActivationChanged;
            Application.DocumentManager.DocumentActivated += DocumentManager_DocumentActivated;

            setwindow();


        }

        private void DocumentManager_DocumentDestroyed(object sender, DocumentDestroyedEventArgs e)
        {
            window.Close();
        }

        private void DocumentManager_DocumentActivated(object sender, DocumentCollectionEventArgs e)
        {
            setwindow();
        }

        private void DocumentManager_DocumentActivationChanged(object sender, DocumentActivationChangedEventArgs e)
        {
            setwindow();
        }

        public void Initialize()
        {
            NFox.Cad.EditorEx.WriteMessage("\nMVVM test starting ");
           // window = new MainView(); // CAD会崩溃
        }

   

        public void Terminate()
        {
            
        }
    }
}
